package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.PageResult;
import com.itheima.constant.QueryPageBean;
import com.itheima.constant.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/15 10:17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    //分页查询;
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = userService.findPage(queryPageBean);
        return pageResult;
    }


    //添加;
    @RequestMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds) {
        try {
            userService.add(user, roleIds);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }
    }

    //根据ID删除;
    @RequestMapping("/deleteByid")
    public Result deleteByid(Integer id) {
        try {
            userService.deleteByid(id);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

    //根据ID查询,用于编辑的页面回显;
    @RequestMapping("/findByid")
    public Result findByid(Integer id) {
        try {
            User user = userService.findByid(id);
            return new Result(true, "查询成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }
    }

    //根据id查询用户关联的角色信息;
    @RequestMapping("/getRoleIds")
    public Result getRoleIds(Integer id) {
        try {
            List<Integer> list = userService.getRoleIds(id);
            return new Result(true, "查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }
    }

    //编辑数据;
    @RequestMapping("/update")
    public Result update(@RequestBody User user, Integer[] roleIds) {
        try {
            userService.update(user, roleIds);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }
}
